import axios, {
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
  AxiosError,
} from "axios";
import { ElMessage } from "element-plus";

const axiosInstance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASEURL, // baseURL 通过.env文件配置
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
  },
});

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // JWT认证, 携带 token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    const { data } = res;
    // 此处 code 为约定值
    if (data.code === 0) {
      return res.data;
    } else {
      ElMessage.error(data.msg);
      return Promise.reject(data.msg);
    }
  },
  (error: AxiosError) => {
    const { response } = error;
    if (response) {
      handleCode(response.status);
    }
    return Promise.reject(error);
  },
);

function handleCode(code: number) {
  switch (code) {
    case 401:
      ElMessage.error("登录失败，请重新登录");
      break;
    default:
      ElMessage.error("请求失败");
      break;
  }
}

export interface ResponseData<T = any> {
  code: number;
  msg: string;
  content: T;
}

export async function get<T>(
  url: string,
  params?: any,
): Promise<ResponseData<T>> {
  return await axiosInstance.get(url, { params });
}

export async function post<T>(
  url: string,
  data?: any,
): Promise<ResponseData<T>> {
  return await axiosInstance.post(url, data);
}

export default axiosInstance;
